<?php

namespace app\api\model\plus\discount;

use app\api\model\plus\discount\Active as DiscountActiveModel;
use app\common\exception\BaseException;
use app\common\model\plus\discount\DiscountGitOrder;
use app\common\model\plus\discount\Product as DiscountProductModel;
use app\api\model\product\Product as ProductModel;
use app\api\model\supplier\Supplier as SupplierModel;
use app\api\model\supplier\ServiceApply;
use app\api\model\plus\discount\Active as ActiveModel;
use think\facade\Cache;
use app\common\model\plus\discount\DiscountGitProduct;
/**
 * 限时秒杀模型
 */
class Product extends DiscountProductModel
{
    /**
     * 隐藏字段
     */
    protected $hidden = [
        'sales_initial',
        'total_sales',
        'is_delete',
        'app_id',
        'create_time',
        'update_time'
    ];

    /**
     * 获取商品列表（用于订单结算）
     */
    public static function getDiscountProduct($params,$user)
    {
        // 任务详情
        $discounts = self::detail($params['discount_product_id'], ['discountSku']);
        if (empty($discounts)) {
            throw new BaseException(['msg' => '商品不存在或已结束']);
        }
        // 商品详情
        $product = ProductModel::detail($discounts['product_id'], ['discountSku']);

        // 积分商品sku信息
        $point_sku = null;
        if ($product['spec_type'] == 10) {
            $point_sku = $discounts['discountSku'][0];
        } else {
            //多规格
            foreach ($discounts['discountSku'] as $sku) {
                if ($sku['discount_product_sku_id'] == $params['discount_product_sku_id']) {
                    $point_sku = $sku;
                    break;
                }
            }
        }
        if ($point_sku == null) {
            throw new BaseException(['msg' => '商品规格不存在']);
        }

        // 商品sku信息
        $product['product_sku'] = ProductModel::getProductSku($product, $params['product_sku_id']);
        $product['discount_sku'] = $point_sku;
        // 商品列表
        $productList = [$product->hidden(['category', 'content', 'image', 'sku'])];
        foreach ($productList as &$item) {

            $item['total_num'] = $params['product_num'];
            $total_price = $point_sku['discount_price'] * $item['total_num'];

            $discount_info = self::getDiscountInfo($item['product_id'],$item['total_num'],$point_sku['discount_price'],$total_price,$user);
            // 商品单价
            $item['product_price'] = $point_sku['discount_price'];
            // 商品购买数量

            $item['spec_sku_id'] = $item['product_sku']['spec_sku_id'];
            // 商品购买总金额
//            $item['total_price'] = $point_sku['discount_price'] * $item['total_num'];
            $item['total_price'] = $discount_info['total_price']??$total_price;

            $item['discount_product_sku_id'] = $point_sku['discount_product_sku_id'];
            $item['product_sku_id'] = $params['product_sku_id'];
            $item['product_source_id'] = $point_sku['discount_product_id'];
            // 活动id
            $item['activity_id'] = $discounts['discount_activity_id'];
            $item['sku_source_id'] = $point_sku['discount_product_sku_id'];
            // 最大购买数
            $item['discount_product'] = [
                'limit_num' => $discounts['limit_num']
            ];
        }

        $supplierData[] = [
            'shop_supplier_id' => $product['shop_supplier_id'],
            'supplier' => $product['supplier'],
            'productList' => $productList,
            'discount_info' => $discount_info
        ];
        unset($product['supplier']);
        return $supplierData;
    }

    //获取商品优惠信息
    public static function getDiscountInfo($product_id,$order_total_num,$price,$total_price,$user){
        $discount_product = DiscountActiveModel::getProductDiscountDetail($product_id);
        $activity_type = $discount_product['activity_type'];//（1=按件数打折，2=首件优惠，按几件起购，3=满赠）

        $map = [];
        $map[] = ['user_id','=',$user['user_id']];
        $map[] = ['pay_status','=',20];
        $map[] = ['product_id','=',$product_id];

        //优惠限制 0=不限制，1=限制用户只有一次优惠
        if((new DiscountGitOrder()) -> where($map) -> count() && $discount_product['limit_user'] == 1){
            return [];
        }

        $is_gift = 0;
        $gift_num = 0;
        $gift_product_id = 0;
        $image_id = 0;
        if($activity_type == 1){
            $rebate = 100;
            $rebate_json = $discount_product['rebate_json'];
            if($rebate_json){
                $count = count($rebate_json);
                foreach ($rebate_json as $key => $value){
                    if($count-2 >= $key){
                        if($order_total_num >= $value['num'] && $order_total_num < $rebate_json[$key+1]['num']){
                            $rebate = $value['rebate'];
                        }
                    }
                    if($rebate_json[$count-1]['num'] <= $order_total_num){
                        $rebate = $rebate_json[$count-1]['rebate'];
                    }

                }
            }
            $total_price = round( $total_price * $rebate/100,2);
        }elseif($activity_type == 2){
            if($discount_product['start_buy_num'] <= $order_total_num){
                $first_price = $discount_product['first_price']; //首件价格
            }else{
                throw new BaseException(['msg' => '该商品'.$discount_product['start_buy_num'].'件起购']);
            }

            $total_price  =$first_price + ($order_total_num-1) * $price;
        }elseif($activity_type == 3){
            $gift_product_id = $discount_product['gift_product']['gift_product_id']??0;
            $image_id = $discount_product['gift_product']['image_id'];
            if($discount_product['buy_num'] <= $order_total_num){
                $is_gift = 1;
                $gift_num = $discount_product['gift_num'];
            }

            $total_price -= $discount_product['discount_moeny'];

        }

        $result_data = [];
        $result_data['is_gift'] = $is_gift;
        $result_data['gift_num'] = $gift_num;
        $result_data['gift_product_id'] = $gift_product_id;
        $result_data['total_price'] = $total_price;
        $result_data['image_id'] = $image_id;
        $result_data['product_id'] = $product_id;
        return $result_data;
    }


    /**
     * 获取首页商品显示
     */
    public function getProductList($discount_activity_id, $limit)
    {
        // 获取列表数据
        $list = $this->alias("a")
            ->with(['product.image.file', 'discountSku'])
            ->join('product product', 'product.product_id=a.product_id')
            ->join('supplier supplier', 'product.shop_supplier_id = supplier.shop_supplier_id', 'left')
            ->where('discount_activity_id', '=', $discount_activity_id)
            ->where('a.is_delete', '=', 0)
            ->where('a.status', '=', 10)
            ->where('a.state', '=', 10)
            ->where('product.is_delete', '=', 0)
            ->where('supplier.is_delete', '=', 0)
            ->where('supplier.status', '=', 0)
            ->where('supplier.is_recycle', '=', 0)
            ->where('product.product_status', '=', 10)
            ->where('product.audit_status', '=', 10)
            ->field('a.*')
            ->limit($limit)
            ->visible(['product.product_id', 'product.product_name', 'product.file_path'])
            ->select();

        foreach ($list as $product) {
            $discount_arr = array_column($product['discountSku']->toArray(), 'discount_price');
            $product_arr = array_column($product['discountSku']->toArray(), 'product_price');
            sort($discount_arr);
            sort($product_arr);
            $product['discount_price'] = current($discount_arr);
            $product['product_price'] = current($product_arr);
            $product['product']['file_path'] = $product['product']['image'][0]['file_path'];
            unset($product['discountSku']);
            unset($product['product']['image']);
        }
        return $list;
    }

    public function getActivityListByUser($discount_activity_id, $userInfo = false)
    {
        $supplier_id = Cache::get($userInfo['user_id'] . '_supplier_id');
        $model = $this->alias("a");

        if ($supplier_id != null) {
            $model = $model->whereIn('product.shop_supplier_id', $supplier_id);
        }
        // 获取列表数据
        $list = $model
            ->with(['product.image.file', 'discountSku'])
            ->join('product product', 'product.product_id=a.product_id')
            ->join('supplier supplier', 'product.shop_supplier_id = supplier.shop_supplier_id', 'left')
            ->where('discount_activity_id', '=', $discount_activity_id)
            ->where('a.is_delete', '=', 0)
            ->where('a.status', '=', 10)
            ->where('a.state', '=', 10)
            ->where('product.is_delete', '=', 0)
            ->where('supplier.is_delete', '=', 0)
            ->where('supplier.status', '=', 0)
            ->where('supplier.is_recycle', '=', 0)
            ->where('product.product_status', '=', 10)
            ->where('product.audit_status', '=', 10)
            ->field('a.*')
            ->visible(['product.product_id', 'product.product_name', 'product.file_path'])
            ->select();

        foreach ($list as $key => &$product) {
            $discount_arr = array_column($product['discountSku']->toArray(), 'discount_price');
            $product_arr = array_column($product['discountSku']->toArray(), 'product_price');
            $product['discount_price'] = current($discount_arr);
            $product['product_price'] = current($product_arr);
            $product['line_price'] = current($product_arr);
            $product['product']['file_path'] = $product['product']['image'][0]['file_path'];
            unset($product['discountSku']);
            unset($product['product']['image']);

//            $discount_arr = array_column($product['discountSku']->toArray(), 'discount_price');
//            $product_arr = array_column($product['discountSku']->toArray(), 'product_price');
//            sort($discount_arr);
//            sort($product_arr);
//            $product['discount_price'] = current($discount_arr);
//            $product['product_price'] = current($product_arr);
//            $product['product']['file_path'] = $product['product']['image'][0]['file_path'];
//            unset($product['discountSku']);
//            unset($product['product']['image']);

        }
        return $list;
    }

    /**
     * 列表页秒杀商品
     * 目前未分页，后续有可能会分页
     */
    public function getActivityList($discount_activity_id)
    {
        // 获取列表数据
        $list = $this->alias("a")
            ->with(['product.image.file', 'discountSku'])
            ->join('product product', 'product.product_id=a.product_id')
            ->join('supplier supplier', 'product.shop_supplier_id = supplier.shop_supplier_id', 'left')
            ->where('discount_activity_id', '=', $discount_activity_id)
            ->where('a.is_delete', '=', 0)
            ->where('a.status', '=', 10)
            ->where('a.state', '=', 10)
            ->where('product.is_delete', '=', 0)
            ->where('supplier.is_delete', '=', 0)
            ->where('supplier.status', '=', 0)
            ->where('supplier.is_recycle', '=', 0)
            ->where('product.product_status', '=', 10)
            ->where('product.audit_status', '=', 10)
            ->field('a.*')
            ->visible(['product.product_id', 'product.product_name', 'product.file_path'])
            ->select();

        foreach ($list as $key => &$product) {
            $discount_arr = array_column($product['discountSku']->toArray(), 'discount_price');
            $product_arr = array_column($product['discountSku']->toArray(), 'product_price');
            $product['discount_price'] = current($discount_arr);
            $product['product_price'] = current($product_arr);
            $product['product']['file_path'] = $product['product']['image'][0]['file_path'];
            unset($product['discountSku']);
            unset($product['product']['image']);

//            $discount_arr = array_column($product['discountSku']->toArray(), 'discount_price');
//            $product_arr = array_column($product['discountSku']->toArray(), 'product_price');
//            sort($discount_arr);
//            sort($product_arr);
//            $product['discount_price'] = current($discount_arr);
//            $product['product_price'] = current($product_arr);
//            $product['product']['file_path'] = $product['product']['image'][0]['file_path'];
//            unset($product['discountSku']);
//            unset($product['product']['image']);

        }
        return $list;
    }

    public function getDiscountDetail($discount_product_id)
    {
        $result = $this->with(['product' => ['image.file', 'contentImage.file'], 'discountSku.productSku.image'])
            ->where('discount_product_id', '=', $discount_product_id)->find();

        if (!empty($result)) {
            $discount_arr = array_column($result->toArray()['discountSku'], 'discount_price');
            $product_arr = array_column($result->toArray()['discountSku'], 'product_price');
            sort($discount_arr);
            sort($product_arr);
            $result['discount_price'] = current($discount_arr);
            $result['line_price'] = current($product_arr);
            $result['rebate_json'] = $result['rebate_json']?json_decode($result['rebate_json'],true):[];
            if (count($discount_arr) > 1) {
                $res['discount_high_price'] = end($discount_arr);
                $res['line_high_price'] = end($product_arr);
            }
            $SupplierModel = new SupplierModel;
            if ($result['shop_supplier_id']) {
                $supplier = $SupplierModel::detail($result['shop_supplier_id'], ['logo', 'category']);
                $supplier['logos'] = $supplier['logo']['file_path'];
                unset($supplier['logo']);
                $supplier['category_name'] = $supplier['category']['name'];
                unset($supplier['category']);
                $supplier->visible(['logos', 'category_name', 'name', 'shop_supplier_id', 'product_sales', 'server_score', 'store_type']);
                $server = (new ServiceApply())->getList($result['shop_supplier_id']);
            } else {
                $supplier = [];
                $server = [];
            }
            $result['supplier'] = $supplier;
            $result['server'] = $server;
        }
        return $result;
    }

    /**
     * 获取正在进行活动的商品id
     * @return array
     */
    public function getDiscountAtivityProduct()
    {
        $Active = new ActiveModel;
        $discountProduct = new DiscountProductModel;
        $map = [];
        $map[] = ['start_time','<=',time()];
        $map[] = ['end_time','>=',time()];
        $map[] = ['status','=',1];
        $discount_activity_ids =  $Active -> where($map) -> column('discount_activity_id');

        $where = [];
        $where[] = ['status','=',10];
        $where[] = ['discount_activity_id','in',$discount_activity_ids];
        $product = $discountProduct -> where($where) -> select();
        $array = [];
        $gift_product_data =  (new DiscountGitProduct()) -> with(['file'])->where('is_delete','=',0) -> field('product_name,product_id,image_id') -> select();
        $gift_data = [];
        foreach ($gift_product_data as $k => $v){
            $v['file_path'] = $v['file']['file_path'];
            unset($v['file']);
            $gift_data[$v['product_id']] = $v;
        }

        foreach ($product as $key => $value){
            $gift_product = $gift_data[$value['product_id']]??[];
            $gift_product['explain'] = $value['explain'];
            $value['gift_product_data'] = $gift_product;

            $value['rebate_json'] = json_decode($value['rebate_json'],true);
            $array[$value['product_id']] = $value;
        }
        return $array;
    }
}
